# code:utf8
import logging
import math
from datetime import datetime
from pyquery import PyQuery
from scrapy.utils.project import get_project_settings
from zc_core.model.items import OrderItem, Catalog, ItemData, Sku
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_number, parse_time
from zc_core.util.encrypt_util import build_sha1_order_id, md5
from zc_core.util.order_deadline_filter import OrderItemFilter
from cmcc.matcher import *
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')
order_filter = OrderItemFilter()


# 解析catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    nav_list = jpy('div.Lnav > dl')
    # nav1_list = jpy('div.nBox > ul > li > a')
    nav1_list = jpy('div.Lnav > dl > dt')

    cats = list()
    cat1_dict = dict()
    for idx, nav1 in enumerate(nav1_list.items()):
        # 一级分类
        cat1 = _build_root_catalog(nav1.text(), idx)
        if cat1.get('catalogId'):
            cats.append(cat1)
            cat1_dict[cat1.get('catalogName')] = cat1

    for dl in nav_list.items():
        # 一级分类
        dt = dl('dt')
        cat1_name = dt.text().strip()
        cat1 = cat1_dict.get(cat1_name)

        if cat1:
            boxes = dl('div.fl_box')
            for box in boxes.items():
                # 二级分类
                nav2_link = box('div.fl_title > a:eq(0)')
                cat2 = _build_catalog(nav2_link, cat1.get('catalogId'), 2)
                cats.append(cat2)

                # 三级分类
                nav3_links = box('div.fl_con > a')
                for nav3_link in nav3_links.items():
                    cat3 = _build_catalog(nav3_link, cat2.get('catalogId'), 3)
                    cats.append(cat3)
    return cats


def _build_root_catalog(text, idx):
    cat = Catalog()
    cat['catalogId'] = 'root_' + str(idx)
    cat['catalogName'] = text.strip()
    cat['parentId'] = ''
    cat['level'] = 1
    cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


def _build_catalog(link, parent_id, level):
    url = link.attr('href')
    cat = Catalog()
    cat['catalogId'] = match_cat_id(url)
    cat['catalogName'] = link.text().strip()
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# 解析sku page列表
def parse_sku_page(response):
    meta = response.meta
    page_size = meta.get('pageSize')
    jpy = PyQuery(response.text)
    total = parse_number(jpy('span.sl strong').text())
    if total and page_size:
        return math.ceil(total / page_size)

    return 0


# 解析sku列表
def parse_sku(response):
    settings = get_project_settings()
    cat_helper = CatalogHelper()
    meta = response.meta
    cat_id = meta.get('catId')
    jpy = PyQuery(response.text)

    no_result = jpy('p.searchNoResults')
    if no_result:
        return None

    lis = jpy('ul.goodsBox li')
    skus = list()
    for li in lis.items():
        sku = Sku()
        # http://b2bjoy.10086.cn/oscp/goods/product/goodsDetail.html?sn=108876
        href = li('p.p_name a').attr('href')
        sku_img = li('p.p_img img').attr('src')
        sku['skuId'] = match_sku_id(href)
        sku['skuName'] = li.attr('goodsname').strip()
        if sku_img:
            sku['skuImg'] = sku_img.replace('/n1/', '/n3/')
        sku['salePrice'] = parse_number(li.attr('goodssaleprice'))
        sku['catalog3Id'] = cat_id
        cat_helper.fill(sku)

        params = li.attr('comparisonparams')
        if params:
            # 洁柔 CR021-01 商用双层200抽塑包面巾纸 3包/提（1）提|8.73|002200070001|提|17.1|史泰博|洁柔|http://b2bjoy.10086.cn/resource/images/xpurchase/goods/n1/1527/223664/1585324510921.jpg|223664
            param_arr = params.split('|')
            if param_arr and len(param_arr) == 9:
                sku['unit'] = param_arr[3]
                sku['originPrice'] = parse_number(param_arr[4], err=sku['salePrice'])
                supplier_name = param_arr[5]
                if supplier_name:
                    sku['supplierName'] = supplier_name.strip()
                    sku['supplierId'] = settings.getdict('SUPPLIERS', {}).get(supplier_name.strip(), None)
                brand = param_arr[6]
                if brand:
                    sku['brandId'] = md5(brand.strip())
                    sku['brandName'] = brand.strip()
        sku['srcContent'] = li.outer_html()

        skus.append(sku)

    return skus


# 解析ItemData
def parse_item_data(response):
    settings = get_project_settings()
    meta = response.meta
    jpy = PyQuery(response.text)

    # 在售标记
    cart = jpy('div#_cart')
    if not cart:
        # 已下架
        return None

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    supplier_sku_id = jpy('input#kc_input_supSn').attr('value')
    if not supplier_sku_id:
        supplier_sku_txt = jpy('div.gtitle:contains("商品编号：") + div.gcon').text()
        supplier_sku_id = match_supplier_sku_id(supplier_sku_txt)
    nav = jpy('div.breadCrumbs a')
    # 10192375 (电商平台\办公文具\办公常用工具及耗材\笔筒)
    material_code = jpy('div.gtitle:contains("物料编码：") + div.gcon').text().strip()
    sale_price = jpy('span#totalPrice').text()
    origin_price = jpy('div.gtitle:contains("市场价格：") + div.gcon span').text()
    supplier_name = jpy('div.gtitle:contains("供 应 商：") + div.gcon').text()
    supplier_id = jpy('input#kc_input_supId').attr('value')
    min_buy = jpy('input#kc_input_minBuy').attr('value')

    supplier_sku_link = jpy('span.monthSale_sp2 a:eq(1)')
    unit = jpy('span#danwei_01').text()
    images = jpy('div#spec-n1 img')

    result = ItemData()
    # -------------------------------------------------
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['materialCode'] = match_material_code(material_code)
    result['skuName'] = jpy('div.breadCrumbs label').attr('title').strip()
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()
    result['catalog1Id'] = match_cat_id(nav.eq(1).attr('href'))
    result['catalog1Name'] = nav.eq(1).text().strip()
    result['catalog2Id'] = match_cat_id(nav.eq(2).attr('href'))
    result['catalog2Name'] = nav.eq(2).text().strip()
    result['catalog3Id'] = match_cat_id(nav.eq(3).attr('href'))
    result['catalog3Name'] = nav.eq(3).text().strip()
    result['salePrice'] = parse_number(sale_price)
    result['originPrice'] = parse_number(origin_price)
    result['unit'] = unit
    brand = nav.eq(4)
    if brand:
        result['brandId'] = match_brand_id(brand.attr('href'))
        result['brandName'] = brand.text().strip()
    if supplier_name and not supplier_id:
        suppliers = settings.getdict('SUPPLIERS', {})
        supplier_id = suppliers.get(supplier_name, None)
    if supplier_id:
        result['supplierId'] = supplier_id.strip()
    if supplier_name:
        sp_name = supplier_name.strip()
        result['supplierName'] = sp_name
    if supplier_sku_id:
        result['supplierSkuId'] = supplier_sku_id.strip()
        plat_code = None
        if supplier_id == '25a547ae759911e6aabc0894ef108494' or '得力' in supplier_name:
            plat_code = 'deli'
        result['supplierSkuCode'] = convert_id2code(plat_code, supplier_sku_id)
    if supplier_sku_link:
        result['supplierSkuLink'] = supplier_sku_link.attr('href').strip()
    if min_buy:
        result['minBuy'] = min_buy
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result


def parse_product_data(response):
    settings = get_project_settings()
    meta = response.meta
    jpy = PyQuery(response.text)

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    supplier_sku_txt = jpy('div.gtitle:contains("商品编号：") + div.gcon').text()
    supplier_sku_id = match_supplier_sku_id(supplier_sku_txt)
    nav = jpy('div.breadCrumbs a')
    # 10192375 (电商平台\办公文具\办公常用工具及耗材\笔筒)
    material_code = jpy('div.gtitle:contains("物料编码：") + div.gcon').text().strip()
    sale_price = jpy('span#totalPrice').text()
    origin_price = jpy('div.gtitle:contains("市场价格：") + div.gcon span').text()
    supplier_name = jpy('div.gtitle:contains("供 应 商：") + div.gcon').text()
    supplier_sku_link = jpy('span.monthSale_sp2 a:eq(0)')
    images = jpy('div#spec-n1 img')

    result = ItemData()
    # -------------------------------------------------
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['materialCode'] = match_material_code(material_code)
    result['skuName'] = jpy('div.breadCrumbs label').attr('title').strip()
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()
    result['catalog1Id'] = match_cat_id(nav.eq(1).attr('href'))
    result['catalog1Name'] = nav.eq(1).text().strip()
    result['catalog2Id'] = match_cat_id(nav.eq(2).attr('href'))
    result['catalog2Name'] = nav.eq(2).text().strip()
    result['catalog3Id'] = match_cat_id(nav.eq(3).attr('href'))
    result['catalog3Name'] = nav.eq(3).text().strip()
    result['salePrice'] = parse_number(sale_price.strip())
    result['originPrice'] = parse_number(origin_price.strip())
    brand = nav.eq(4)
    if brand:
        result['brandId'] = match_brand_id(brand.attr('href'))
        result['brandName'] = brand.text().strip()
    if supplier_name:
        result['supplierName'] = supplier_name.strip()
        suppliers = settings.getdict('SUPPLIERS', {})
        result['supplierId'] = suppliers.get(supplier_name.strip(), None)
    if supplier_sku_id:
        result['supplierSkuId'] = supplier_sku_id.strip()
        plat_code = None
        if '得力' in supplier_name:
            plat_code = 'deli'
        result['supplierSkuCode'] = convert_id2code(plat_code, supplier_sku_id)
    if supplier_sku_link:
        result['supplierSkuLink'] = supplier_sku_link.attr('href').strip()
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result


# 解析order列表
def parse_order_item(response):
    jpy = PyQuery(response.text)
    meta = response.meta
    sku_id = meta.get('skuId')
    supplier_name = jpy('div.gtitle:contains("供 应 商：") + div.gcon').text().strip()

    orders = list()
    need_next_page = True
    tr_list = jpy('div.dataTable tbody tr')
    if tr_list and len(tr_list):
        prev_order = None
        same_order_no = 1
        for idx, tr in enumerate(tr_list.items()):
            tds = tr('td')
            # <td colspan="4">该商品近30天无销售记录</td>
            if tds and len(tds) > 1:
                # 采购时间  2018-12-14 11:18
                order_time_str = tds.eq(3).text()
                order_time = parse_time(order_time_str, fmt='%Y-%m-%d %H:%M')
                if order_filter.to_save(order_time):
                    order = OrderItem()
                    order['skuId'] = sku_id
                    amount = match_amount(tds.eq(2).text().strip())
                    order['count'] = round(parse_number(amount))
                    order['amount'] = parse_number(tds.eq(1).text().strip())
                    # 用户  l******@zj.cmcc<br />浙江公司
                    user = tds.eq(0).html().split('<br />')
                    order['orderUser'] = user[0]
                    if user[1]:
                        order['orderDept'] = user[1]
                    else:
                        # 兼容一些采购单位名称为空的订单
                        order['orderDept'] = '未知'
                    order['supplierName'] = supplier_name
                    order['orderTime'] = order_time
                    order['batchNo'] = time_to_batch_no(order_time)
                    order['genTime'] = datetime.utcnow()
                    if prev_order and prev_order.equals(order):
                        same_order_no = same_order_no + 1
                    else:
                        same_order_no = 1
                    addition = {
                        'sameOrderNo': same_order_no,
                        'orderTimeStr': order_time_str,
                    }
                    sha1_id = build_sha1_order_id(order, addition)
                    order['id'] = sha1_id
                    order['orderId'] = sha1_id
                    orders.append(order)
                    prev_order = order
                else:
                    need_next_page = False
    else:
        need_next_page = False
        logger.info('无单[%s]', sku_id)

    return orders, need_next_page


# 订单总页数
def parse_total_page(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    # 当前第1条到第15条记录,共15条记录
    span = jpy('div#www_saleRecord div.read_page1 span:last')
    if span and span.text():
        total_order = match_total_order(span.text())
        size = int(meta.get('orderPageSize'))
        if total_order > size:
            return int(math.ceil(total_order / size))

    return 1
